import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:screenshot/screenshot.dart';
import 'package:timeago/timeago.dart' as timeago;
import '../model/note.dart';
import '../util/permission.dart'; // 用于文件保存


class NoteDetailScreen extends StatelessWidget {
  final Note note;
  final ScreenshotController screenshotController = ScreenshotController();

  NoteDetailScreen({required this.note});

  // 导出为 TXT
  Future<void> exportAsTxt() async {

    final hasPermission = await PermissionUtils.checkFileSavePermission();
    if (!hasPermission) {
      Get.snackbar('Error', 'Permission denied to save file');
      return;
    }

    final content = 'Title: ${note.title}\n\nContent: ${note.content}\n\nCategory: ${note.categoryName}\n\nCreated: ${note.createdAt}\n\nUpdated: ${note.updatedAt}';
    final fileName = '${note.title}.txt';

    try {
      // 1. 获取用户选择的保存路径
      String? savePath = await FilePicker.platform.saveFile(
        fileName: fileName,
        type: FileType.custom,
        allowedExtensions: ['txt'], // 限制为txt文件
        dialogTitle: 'Save as TXT', // 自定义对话框标题
      );

      if (savePath == null) {
        return; // 用户取消操作
      }

      // 2. 将数据写入文件
      final File file = File(savePath);
      await file.writeAsBytes(content.codeUnits); // 直接写入字节数据

      Get.snackbar('Success', 'Note exported as TXT');
    } catch (e) {
      Get.snackbar('Error', 'Failed to save file: ${e.toString()}');
    }

  }

  // 导出为图片
  Future<void> exportAsImage() async {

    final hasPermission = await PermissionUtils.checkImageSavePermission();
    if (!hasPermission) {
      Get.snackbar('Error', 'Permission denied to save image');
      return;
    }
    try {

      // 截图捕获
      final image = await screenshotController.capture();
      if (image == null) return;

      // 生成文件名（自动补全.png后缀）
      final fileName = note.title.replaceAll(RegExp(r'[^\w-]'), '_'); // 清理非法字符
      final safeFileName = fileName.endsWith('.png') ? fileName : '$fileName.png';

      // 获取用户选择的保存路径
      String? savePath = await FilePicker.platform.saveFile(
        fileName: safeFileName,
        type: FileType.custom,
        allowedExtensions: ['png'], // 限制为PNG格式
        dialogTitle: 'Save as PNG Image',
      );

      if (savePath == null) return; // 用户取消操作

      // 强制添加.png后缀（防止用户手动删除后缀）
      if (!savePath.endsWith('.png')) {
        savePath += '.png';
      }

      // 写入文件
      final File file = File(savePath);
      final sink = file.openWrite();
      sink.add(image);
      await sink.close();
      Get.snackbar('Success', 'Note exported as Image');
    } catch (e) {
      Get.snackbar('Error', 'Failed to save image: ${e.toString()}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Note Detail'),
        actions: [
          IconButton(
            icon: Icon(Icons.edit),
            onPressed: (){

            }, // 导出为 TXT
          ),
          IconButton(onPressed: (){
            Get.bottomSheet(
              Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.vertical(top: Radius.circular(16)),

                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    ListTile(
                      leading: Icon(Icons.edit_document),
                      title: Text('导出文字（txt）'),
                      onTap: () {
                        Get.back(); // 关闭菜单
                        // Get.find<CameraController>().takePhoto();
                      },
                      titleAlignment: ListTileTitleAlignment.center,
                    ),
                    Divider(
                      height: 0.5,
                    ),
                    ListTile(
                      leading: Icon(Icons.photo_library),
                      title: Text('导出图片（png）'),
                      titleAlignment: ListTileTitleAlignment.center,
                      onTap: () {
                        Get.back();
                      },
                    ),
                    Divider(
                      height: 0.5,
                    ),
                    SizedBox(
                      height: 16,
                    )
                  ],
                ),
              ),
              barrierColor: Colors.black54, // 遮罩透明度
              isScrollControlled: true,     // 自适应高度
            );
          }, icon: Icon(Icons.more_vert_rounded))
          // IconButton(
          //   icon: Icon(Icons.text_snippet),
          //   onPressed: exportAsTxt, // 导出为 TXT
          // ),
          // IconButton(
          //   icon: Icon(Icons.image),
          //   onPressed: exportAsImage, // 导出为图片
          // ),
        ],
      ),
      body:  SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              note.title,
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Text(
              note.content,
              style: TextStyle(fontSize: 16),
            ),
            SizedBox(height: 8),
            Divider(
              height: 0.5,
            ),
            Text(
             '分类: ${note.categoryName}',
              style: TextStyle(fontSize: 14, color: Colors.grey),
            ),
            Text('字数: ${note.content.length}',style: TextStyle(fontSize: 14, color: Colors.grey),),
            SizedBox(height: 8),
            Text(
              '创建于: ${timeago.format(note.createdAt,locale: 'zh_CN')}',
              style: TextStyle(fontSize: 14, color: Colors.grey),
            ),
            SizedBox(height: 8),
            Text(
              '最后更新: ${timeago.format(note.updatedAt,locale: 'zh_CN')}',
              style: TextStyle(fontSize: 14, color: Colors.grey),
            ),
          ],
        ),
      )
    );
  }
}